<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 每日工作报工管理
 */
class DailyWorkReport extends Backend
{
    /**
     * DailyWorkReport模型对象
     * @var \app\admin\model\scanwork\DailyWorkReport
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\DailyWorkReport;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自定义
     * 如果需要自定义，请复制application/admin/library/traits/Backend.php中对应的方法来修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['workitems'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['workitems'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id','work_date','remark','status','audit_reason','audit_time','audit_user_id','createtime','updatetime']);
                $row->visible(['workitems']);
                $row->getRelation('workitems')->visible(['id','daily_report_id','order_id','model_id','process_id','quantity','work_hours','work_description']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->with(['workitems.images'])->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取关联数据
        $workItems = $row->workitems;
        foreach ($workItems as $item) {
            // 获取订单信息
            $order = Db::name('scanwork_order')->where('id', $item->order_id)->find();
            $item->order_info = $order;
            
            // 获取产品型号信息
            $model = Db::name('scanwork_model')->where('id', $item->model_id)->find();
            if ($model) {
                $product = Db::name('scanwork_product')->where('id', $model['product_id'])->find();
                $model['product_name'] = $product ? $product['name'] : '';
            }
            $item->model_info = $model;
            
            // 获取工序信息
            $process = Db::name('scanwork_process')->where('id', $item->process_id)->find();
            $item->process_info = $process;
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function audit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
